package com.hibase.core.excel.validator;

import com.google.common.collect.Maps;
import com.hibase.common.exception.HibaseException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Map;
import java.util.Set;

/**
 * hibernate-validator校验工具类
 *
 * @author <a href="mailto:xiongliyi@hichain.com">Ian Xiong</a>
 * @since 1.4.35-V2
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     */
    public static Map<String, String> validateEntity(Object object, Class<?>... groups)
            throws HibaseException {
        // key: 列的序号 ，value: 错误信息
        Map<String, String> errorMap = Maps.newHashMap();
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {

            for (ConstraintViolation<Object> constraint : constraintViolations) {
                errorMap.put(null, constraint.getMessage());
            }
        }
        return errorMap;
    }
}
